import * as React from 'react';
import classNames from 'classnames';
import Input, { InputProps } from './Input';
import Button, { ButtonType } from '../view-abutton';

export interface SearchProps extends InputProps {
  inputPrefixCls?: string;
  onSearch?: (value: string) => any;
  enterButton?: boolean | React.ReactNode;
  enterButtonType?: ButtonType;
}

export default class Search extends React.Component<SearchProps, any> {
  static defaultProps = {
    inputPrefixCls: 'cube-input',
    prefixCls: 'cube-input-search',
    enterButton: false,
  };
  state = {
    focus: false
  }
  private input: Input;

  onSearch = () => {
    const { onSearch } = this.props;
    if (onSearch) {
      onSearch(this.input.input.value);
    }
    this.input.focus();
  }

  handleFocus = (e) => {
    const { onFocus } = this.props;
    this.setState({ focus: true });
    if (onFocus) {
      onFocus(e)
    }
  }
  handleBlur = (e) => {
    this.setState({ focus: false });
    const { onBlur } = this.props;
    if (onBlur) {
      onBlur(e)
    }
  }
  focus() {
    this.input.focus();
  }

  blur() {
    this.input.blur();
  }

  saveInput = (node: Input) => {
    this.input = node;
  }

  render() {
    const { className, prefixCls, inputPrefixCls, size, enterButton, enterButtonType, suffix, ...others } = this.props;
    delete (others as any).onSearch;
    const buttonOrIcon = enterButton
      ? (
        <Button
          className={`${prefixCls}-button`}
          type={enterButtonType}
          size={size}
          onClick={this.onSearch}
          key="enterButton"
        >
          {enterButton === true ? <i className="anticon anticon-search" /> : enterButton}
        </Button>
      ) : <Button
              className={`${prefixCls}-button`}
              type={enterButtonType}
              size={size}
              onClick={this.onSearch}
              key="enterButton"
            ><i className={`${prefixCls}-icon anticon anticon-search`} key="searchIcon" /></Button>;
    const searchSuffix = suffix ? [suffix, buttonOrIcon] : buttonOrIcon;
    const inputClassName = classNames(prefixCls, className, {
      [`${prefixCls}-enter-button`]: !!enterButton,
      [`${prefixCls}-${size}`]: !!size,
      [`${prefixCls}-focus`]: this.state.focus
    });
    return (
      <Input
        onPressEnter={this.onSearch}
        {...others}
        size={size}
        className={inputClassName}
        prefixCls={inputPrefixCls}
        suffix={searchSuffix}
        ref={this.saveInput}
        onFocus={this.handleFocus}
        onBlur={this.handleBlur}
      />
    );
  }
}
